<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class HomeBlock extends BaseAction {

    /**
     * 访问日志
     */
    public function accessBlock() {
        //header('Content-Type:text/html;charset:utf-8');
        define('DEBUG', false);

        $uhash = getRequestUhash();
        $url = $this->getUrl($uhash);

        if($url == null) {
            $this->redirect('/');
        }


        if (empty($_SESSION['tmp']['uid'])) {
            $uid = 0;
        } else {
            $uid = $_SESSION['tmp']['uid'];
        }
        $ip = getIp();
        $time   = date('Ymd');
        //记录PV
        //$acc    = DB_ACCESS::writeAccess($uhash);
        //$sql = "call updateCountVoid('$uhash','$ip',$uid); " . getBr();
        //记录今日pv
        //DB_COUNT_PV::writeTodayPv($uhash);
        
        /**
         * 记录当前时段PV
         */
        $sql    = "INSERT u22_count_pv (uhash,log_time,uid) VALUES(?,?,?)  ON DUPLICATE KEY UPDATE pv=pv+1";
        $exec   = DAO_Finder::exec($sql, 'DB_IP', array($uhash,$time,$uid));

        $total  = DAO_Finder::findCount('DB_ACCESS', array('uhash' => $uhash,'ip' => $ip), 'id');
        $uid = 0;
        //独立的IP
        if($total == 0) {
            $sql    = "UPDATE u22_url SET total_ip=total_ip +1 WHERE uhash = ?";
            DAO_Finder::exec($sql, 'DB_USER', array($uhash));
            $debug[]  = array('sql' =>$sql, 'param' => array($uhash));

            $sql    = "INSERT INTO u22_ip (uhash ,ip,created,uid)VALUES (?,?,?,?)";
            DAO_Finder::exec($sql, 'DB_IP', array($uhash, $ip, time(), $uid));

            $debug[]  = array('sql' =>$sql, 'param' => array($uhash, $ip, time(),$uid));

            $sql    = "INSERT u22_count_ip (uhash,log_time,uid) VALUES(?,?,?)  ON DUPLICATE KEY UPDATE ip=ip+1";
            

            $debug[]  = array('sql' =>$sql, 'param' => array($uhash,$time,$uid));
            DAO_Finder::exec($sql, 'DB_IP', array($uhash,$time,$uid));

            if(DEBUG) {
                print_r($debug);
            }
        }

        //记录访问
        $acc    = DB_ACCESS::writeAccess($uhash);

        if(DEBUG) {
            print_r($acc);
        }
        //FileWrite::writeTableAccess($sql);

        //更新url点击表

        $sqlQuery   = "update `u22_url` set total_pv =total_pv+1 where uhash='$uhash'";
        DAO_Finder::exec($sqlQuery);

        if(DEBUG) {
            print_r($sqlQuery);
        }

        //记录操作系统
        $os = getOsName();
        //FileWrite::writeTableOs($uid, $uhash, $os);
        $sql= "INSERT u22_url_os (uid,uhash, name) values (?,?, ?) ON DUPLICATE KEY UPDATE click=click+1";
        DAO_Finder::exec($sql,DB_USER,array($uid, $uhash, $os));

        $debug[]  = array('sql' =>$sql, 'param' => array($uid, $uhash, $os));
        //来源
        //$referer    = getReferer();
        //$referer    = Common::pregDomain($rederer);;
        //FileWrite::writeTableReferer($uid, $uhash, $referer);
        
        //记录浏览器
        $ie = getIeName();
        //FileWrite::writeTableIe($uid, $uhash, $ie);
        $sql= "INSERT u22_url_ie (uid,uhash, name) values (?,?, ?) ON DUPLICATE KEY UPDATE click=click+1";
        DAO_Finder::exec($sql, 'DB_USER', array($uid, $uhash, $ie));

        $debug[]  = array('sql' =>$sql, 'param' => array($uid, $uhash, $ie));
        
        //记录蜘蛛
        $spider = getRoots();
        //FileWrite::writeTableSpider($uid, $uhash, $spider);
        if(!empty($spider)) {
            $sql    = "INSERT u22_url_spider (uid,uhash, name) values (?,?,?) ON DUPLICATE KEY UPDATE click=click+1";
            DAO_Finder::exec($sql,  'DB_USER', array($uid, $uhash, $spider));
            $debug[]  = array('sql' =>$sql, 'param' => array($uid, $uhash, $spider));
        }

         //记录省份
        $ip = getIp();
        $pro    = convertip($ip);
        if(DEBUG) {
            echo $pro.'<br/>';
        }
        
        if(preg_match('~省~', $pro, $p)) {
           $pro    = explode('省', $pro);
           $pro = trim($pro[0]);
        }elseif(preg_match('~市~', $pro, $p)) {
           $pro    = explode('市', $pro);
           $pro = trim($pro[0]);
        }else{
            $pro    = '未知';
        }

        //省份
        //FileWrite::writeTableProvince($uid, $uhash, $local['province']);
        $sql    = "INSERT u22_url_province (uid,uhash, name) values (?,?,?) ON DUPLICATE KEY UPDATE click=click+1";
        //$pro    = $local['province'];
        $insert = array($uid, $uhash, $pro);
        DAO_Finder::exec($sql, 'DB_USER', $insert);

        if(DEBUG) {
            print_r($insert);
        }
        
        if(DEBUG) {
            print_r($debug);
        }else{
            //$this->redirect($url, 302);
        }
        header('Found');
        header('Location: '.$url);
    }

    /**
     * 获取网址
     * @param <type> $uhash
     * @return string
     */
    public function getUrl($uhash) {
        $url = getHashUrl($uhash);
        if (empty($url)) {
            $acc = DAO_Finder::findOne(DB_URL, array('uhash' => "$uhash"), 'url');
            if (!empty($acc)) {
                $url = $acc->getUrl();
                $url->save();
            } else {
                return null;
            }
        }
        return $url;
    }

    //月份统计
    public function mothCountBlock() {
        $endTime = strtotime(date("Y-m-d 23:59:59"));
        $startTime = $endTime - (3600 * 24 * 31);
        $date = array();
        for ($i = $startTime; $i <= $endTime; $i++) {
            $day = date('d', $i);
            $date[$day] = array('start' => strtotime(date('Y-m-d 00:00:00', $i)), 'end' => $i);
            $i = $i + (3600 * 24) - 1;
        }
    }

    /**
     * 获取新浪短网址
     * get_block('home', 'get_sina_url',array('url'=>'要缩短的网址'));
     */
    public function getSinaUrlBlock() {
        $baseUrl = 'http://'.$_SERVER['HTTP_HOST'].'/cgi/sina/short_url.php?q=' . base64_encode($this->params['url']);
        $request = new HTTP_Request($baseUrl);
        $request->sendRequest();
        $_SESSION['sina_url'] = trim($request->getResponseBody());
    }
    /**
     * 获取腾讯短网址
     * get_block('home', 'get_tencent_url',array('url'=>'要缩短的网址'));
     */
    public function getTencentUrlBlock() {
        $baseUrl = 'http://'.$_SERVER['HTTP_HOST'].'/cgi/tencent/short_url.php?q=' . base64_encode($this->params['url']);
        $request = new HTTP_Request($baseUrl);
        $request->sendRequest();
        $_SESSION['tencent_url'] = trim($request->getResponseBody());
    }

    public function setUrlUidBlock() {
        $uhash   = Cookies::getMine('u22_url');
        if(!empty($uhash)) {
            $uid    = $_SESSION['user']['id'];
            $uhash   = "'".str_replace(',', "','", $uhash)."'";
            $sql     = "update u22_url set uid=$uid where uhash in($uhash)";
            DAO_Finder::querySQl($sql);
            Cookies::remove('u22_url');
        }
    }

}

?>
